﻿/// <reference path="P3.Core.js" />
/// <reference path="P3.Core.SharePointClient.js" />
/// <reference path="P3.Core.SPClientJQuery.js" />
/// <reference path="P3.Core.Settings.js" />
/// <reference path="JQuery/jquery-ui.min.js" />
/// <reference path="JQuery/jquery.min.js" />
/// <reference path="jquery.fabric.min.js" />
/// <reference path="~/_layouts/15/init.js" /> 
/// <reference path="~/_layouts/15/SP.Core.js" /> 
/// <reference path="~/_layouts/15/SP.Runtime.js" /> 
/// <reference path="~/_layouts/15/SP.UI.Dialog.js" /> 
/// <reference path="~/_layouts/15/SP.js" />

//ExecuteOrDelayUntilScriptLoaded(InitBase, "sp.js");

var notifyP3Id = ''
var p3CoreSPClient;
var allP3Features = [];
_spBodyOnLoadFunctionNames.push("InitBase");

function InitBase() {
    //SP.SOD.executeFunc('sp.js','SP.ClientContext', function(){
    var feature = new Feature('1917fec6-620a-483f-a9fa-1963dd0e7887', 'P3 Core', 'Basic functionalities for all P3 modules', 'P3CoreStart.aspx', '/_layouts/15/images/siteIcon.png', 'P3ModulesCore', FeatureScope.Web);
    p3CoreSPClient = new P3CoreSharePointClient(feature);
    
    if (typeof jQuery == 'undefined')
        {
            var headTag = document.getElementsByTagName("head")[0];
            var jqTag = document.createElement('script');
            jqTag.type = 'text/javascript';
            jqTag.src = p3CoreSPClient.baseUrl + '/P3/Scripts/JQuery/jquery.min.js';
            headTag.appendChild(jqTag);
    }
    if (typeof (webServerRelativeUrl) == 'undefined'){
        notifyP3Id = SP.UI.Notify.addNotification("Initializing P3 tools...", false);
        writeToP3Core();
        }
    //if (typeof fabric !== 'undefined')
    //    document.write("<script type='text/javascript' src='" + p3CoreSPClient.baseUrl + "/P3/Scripts/jquery.fabric.min.js'></script>");
    //notify script has loaded 
    SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("P3.Core.Init.js");
    //});
}

function Feature(id, title, description, settingsUrl, tileImage, internalName, scope) {
    this.id = id;
    this.title = title;
    this.description = description;
    this.settingsUrl = settingsUrl;
    this.tileImage = tileImage;
    this.internalName = internalName;
    this.scope = scope;
    this.settings = {};
}

function P3CoreSharePointClient(feature) {

    function initFeatures(features) {
        var dfd = $.Deferred();
        var ctx = SP.ClientContext.get_current();
        var properties = ctx.get_web().get_allProperties();
        var featurestring = "";
        var featureArray = {};
        ctx.load(properties);
        ctx.load(features, 'Include(DefinitionId)');
        ctx.executeQueryAsync(
        Function.createDelegate(this, function () {
            try {
                var values = properties.get_fieldValues();
                for (var key in values) {
                    if ((values.hasOwnProperty(key)) && (typeof values[key] !== 'function') && (key.startsWith("P3_"))) {
                        var propertiesPart1 = values[key].split(',');
                        var id = propertiesPart1[0].toLowerCase();
                        var featureEnumerator = features.getEnumerator();
                        while (featureEnumerator.moveNext()) {
                            var feature = featureEnumerator.get_current();
                            featureString += feature.get_definitionId().tolowerCase();
                        }
                        if (featureString.contains(id)) {
                            var featureObject = new Feature(id, propertiesPart1[1], propertiesPart1[2], propertiesPart1[3], propertiesPart1[4], propertiesPart1[5]);
                            featureArray.push(featureObject);
                            obj.feature = featureObject;
                        }
                    }
                }
                dfd.resolve(featureArray);
            } catch (e) {
                dfd.reject(e.message)
            }
        }),
            Function.createDelegate(this, function (sender, args) {
                dfd.reject(error);
            })
        );
        return dfd.promise();
    }


    this.webFeatures = {};
    this.siteFeatures = {};
    this.feature = feature;
    this.allSettings = JSON.parse(p3CoreSettingsString); 
    this.feature.settings = this.allSettings[feature.id];
    this.globalOverrideCtx = {
        Templates: {
            Fields: {},
            Item: {},
            Group: {},
            Header: {},
            Body: {},
            Footer: {},
            View: {}
        },
        OnPostRender: {},
        OnPreRender: {},
        Header: {},
        Footer: {}
    };


    if (feature.scope == FeatureScope.Web) {
        if (typeof (webServerRelativeUrl) != 'undefined')
            this.baseUrl = webServerRelativeUrl; 
    }
    else
        if (feature.scope == FeatureScope.Site) {
            if (typeof (siteServerRelativeUrl) != 'undefined')
                this.baseUrl = siteServerRelativeUrl;
        }
    if (typeof (siteServerRelativeUrl) != 'undefined')
        this.SiteCollUrl = siteServerRelativeUrl;

    this.openSettingsPage = function () {
        var promise;
        if (this.feature == null) {
            if ((featureScope == FeatureScope.Site)||(featureScope == FeatureScope.List)||(featureScope == FeatureScope.ContenType))
                promise = this.getSiteFeatures(this);
            else
                if (featureScope == FeatureScope.Web)
                    promise = this.getWebFeatures(this);
            promise.then(SP.UI.ModalDialog.showModalDialog({ url: this.feature.settingsUrl }), showMessage(error, true));
        } else
            SP.UI.ModalDialog.showModalDialog({ url: this.feature.settingsUrl })
    }

    this.getWebFeatures = function (obj) {
        var dfd = $.Deferred();

        initFeatures(
           SP.ClientContext.get_current().get_web().get_features()).then(function (features) { obj.webFeatures = features; dfd.resolve(); }, function (error) { dfd.reject(error) });
        return dfd.promise();
    }
    this.getSiteFeatures = function (obj) {
        var dfd = $.Deferred();
        initFeatures(
             SP.ClientContext.get_current().get_site().get_features()).then(function (features) { obj.siteFeatures = features; dfd.resolve(); }, function (error) { dfd.reject(error) });
        return dfd.promise();
    }

}

function writeToP3Core()
{
    var folderpath;
    var webServerUrl = _spPageContextInfo.webServerRelativeUrl;
    if (webServerUrl.charAt(webServerUrl.length - 1) == '/')
        folderpath = "P3/Scripts";
    else
        folderpath = "/P3/Scripts";

    req = AllBrowserWebRequest();
    req.open("GET", window.location.protocol + "//" + window.location.host +_spPageContextInfo.webServerRelativeUrl + folderpath + "/P3.Core.Settings.js");
    req.onreadystatechange = function (a, b) {
        if ((req.status == 200) && (req.readyState == 4))
            ExecuteOrDelayUntilScriptLoaded(
                           function () {
                               var appendtext = 'var webServerRelativeUrl = \'' + _spPageContextInfo.webServerRelativeUrl + '\';' + 'var siteServerRelativeUrl = \'' + _spPageContextInfo.siteServerRelativeUrl + '\';';
                               createFile(SP.ClientContext.get_current(), req.responseText + appendtext, _spPageContextInfo.webServerRelativeUrl + folderpath, "P3.Core.Settings.js")
                               .done(
                                              function (sender, args) {
                                                  if (notifyP3Id != '') {
                                                      SP.UI.Notify.removeNotification(notifyP3Id);
                                                      notifyP3Id = '';
                                                  }
                                              }
                               ).fail(
                                              function (err) {
                                                  if (notifyP3Id != '') {
                                                      SP.UI.Notify.removeNotification(notifyP3Id);
                                                      notifyP3Id = '';
                                                  }
                                              }
                               );
                           }, "sp.js");
    };
    req.send(null);

}

